﻿using MediatR;
using WMS.Api.Application.Commands.Users;
using WMS.Common;
using WMS.Domain;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers.Users
{
    public class DelUserCommandHandler : IRequestHandler<DelUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<User> _userRepo;

        public DelUserCommandHandler(IBaseRepository<User> userRepo)
        {
            _userRepo = userRepo;
        }

        public async Task<ApiResult<int>> Handle(DelUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>("删除用户");

            // 检查用户是否存在
            var existingUser = await _userRepo.GetValueByIdAsync(request.Id);
            if (existingUser == null)
            {
                result.isSuc = false;
                result.data = 0;
                result.msg = "用户不存在";
                result.code = StatusCodeEnum.Fail;
                return result;
            }

            // 使用DelDataAsync根据ID删除用户（根据id批量删除 真删除）
            var r = await _userRepo.DelDataAsync(u => u.UserId == request.Id);

            // 如果需要使用DelAll方法（批量删除），则这样调用：
            // var userList = new List<User> { existingUser };
            // var r = await _userRepo.DelAll(userList);

            result.data = r;
            result.isSuc = true;
            result.msg = "删除成功";
            result.code = StatusCodeEnum.Ok;

            if (r < 0)
            {
                result.isSuc = false;
                result.data = 0;
                result.msg = "删除失败";
                result.code = StatusCodeEnum.Fail;
            }

            return result;
        }
    }
}
